import {createRouter, createWebHashHistory} from 'vue-router'
import {showFailToast} from "vant";
import {clearUserLoginStatus, getUserLoginStatus} from "@/utils/userIsLogin";

const router = createRouter({
    history: createWebHashHistory(),
    routes: [
        {
            path: '/',
            name: 'index',
            component: () => import('@/views/Index/index.vue'),
            children: [
                {
                    path: 'home',
                    name: 'home',
                    component: () => import('@/views/Home/index.vue')
                },
                {
                    path: 'video',
                    name: 'video',
                    component: () => import('@/views/Videos/index.vue')
                },
                {
                    path: 'mine',
                    name: 'mine',
                    component: () => import('@/views/Mine/index.vue')
                }
            ]
        },
        {
            path: '/news/:id',
            name: 'news',
            component: () => import('@/views/News/index.vue')
        },
        {
            path: '/login',
            name: 'login',
            component: () => import('@/views/Login/index.vue')
        },
        {
            path: '/add',
            name: 'add',
            component: () => import('@/views/Add/index.vue'),
            meta: {
                requiresAuth: true,// 添加该字段，表示进入这个路由是需要登录的
                requiresMessage:'新增页面需要登陆'
            }
        }
    ]
})
// 全局前置守卫，用于实现路由鉴权
router.beforeEach((to, from, next) => {
    if (to.matched.some(record => record.meta.requiresAuth)) {
        const isLoggedIn = getUserLoginStatus();// 判断用户是否已经登录
        console.log(isLoggedIn)
        // 需要登录才能访问该页面
        if (!isLoggedIn) {
            const requiresMessage = to.meta.requiresMessage || '请先登录';
            showFailToast(requiresMessage);
            clearUserLoginStatus();
            // 用户未登录，跳转到登录页面
            next('/login');
        } else {
            // 用户已登录，继续访问该页面
            next();
        }
    } else {
        // 不需要登录即可访问该页面
        next();
    }
});

export default router
